#include "qst_sw_i2c.h"
#include "asm/iic_soft.h"

#define iic_hdl 0

#define i2c_Start() soft_iic_start(iic_hdl)
#define i2c_SendByte(byte) soft_iic_tx_byte(iic_hdl, byte)
#define i2c_Stop() soft_iic_stop(iic_hdl)
#define i2c_ReadByte(ack) soft_iic_rx_byte(iic_hdl, ack)

uint8_t qst_sw_writereg(uint8_t slave, uint8_t reg_add, uint8_t reg_dat)
{
	i2c_Start();

	if (i2c_SendByte(slave))
	{
		return 0;
	}
	if (i2c_SendByte(reg_add))
	{
		return 0;
	}
	i2c_Start();
	if (i2c_SendByte(reg_dat))
	{
		return 0;
	}
	i2c_Stop();

	return 1;
}

uint8_t qst_sw_writeregs(uint8_t slave, uint8_t reg_add, uint8_t *reg_dat, uint8_t len)
{
	uint8_t i;

	i2c_Start();
	;
	if (i2c_SendByte(slave))
	{
		return 0;
	};
	if (i2c_SendByte(reg_add))
	{
		return 0;
	}
	for (i = 0; i < len; i++)
	{
		;
		if (i2c_SendByte(reg_dat[i]))
		{
			return 0;
		}
	}
	i2c_Stop();

	return 1;
}

uint8_t qst_sw_readreg(uint8_t slave, uint8_t reg_add, uint8_t *buf, uint16_t num)
{
	// uint8_t ret;
	uint16_t i;

	i2c_Start();

	if (!i2c_SendByte(slave))
	{
		printf("send slave erro");
		return 0;
	}

	if (!i2c_SendByte(reg_add))
	{
		printf("send reg_add erro");
		return 0;
	}
	i2c_Start();

	if (!i2c_SendByte(slave + 0x01))
	{
		printf("send slave + 1 erro");
		return 0;
	}

	for (i = 0; i < (num - 1); i++)
	{
		printf("i = %d %d \n", i, buf[i]);
		*buf = i2c_ReadByte(1);
		buf++; 
	}
	*buf = i2c_ReadByte(0);
	i2c_Stop();

	return 1;
}

u8 read_one_byte(u8 addr, u8 *data)
{
	i2c_Start();
	if (!i2c_SendByte(MT6701_IIC_ADDR))
		return 0;

	if (!i2c_SendByte(addr))
		return 0;
	i2c_Start();

	if (!i2c_SendByte(MT6701_IIC_ADDR + 0x01))
		return 0;

	*data = i2c_ReadByte(0);
	data++;
	*data = i2c_ReadByte(0);
	i2c_Stop();
}
